import { createFileRoute } from '@tanstack/react-router'
import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { StorageService, generateId } from '../services/storage'
import { BucketItemForm } from '../components/BucketItemForm'
import { CompletionModal } from '../components/CompletionModal'

interface BucketItem {
  id: number
  text: string
  completed: boolean
  category: string
  completedDate?: string
  completedNote?: string
}

function BucketList() {
  const [bucketItems, setBucketItems] = useState<BucketItem[]>([])
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingItem, setEditingItem] = useState<BucketItem | null>(null)
  const [showCompletionModal, setShowCompletionModal] = useState<BucketItem | null>(null)

  // 加载数据
  useEffect(() => {
    const savedItems = StorageService.getBucketList()
    if (savedItems.length > 0) {
      setBucketItems(savedItems)
    } else {
      const defaultItems: BucketItem[] = [
        { id: 1, text: "一起去看北极光", completed: false, category: "旅行" },
        { id: 2, text: "学会做对方最爱的菜", completed: true, category: "技能", completedDate: "2024-01-15", completedNote: "终于学会了她最爱的糖醋里脊，看到她幸福的表情真的太值得了！" },
        { id: 3, text: "养一只小猫咪", completed: false, category: "生活" },
        { id: 4, text: "一起看日出日落", completed: true, category: "浪漫", completedDate: "2024-02-01", completedNote: "在海边看日出，那一刻觉得世界都静止了，只有我们两个人。" },
        { id: 5, text: "去迪士尼乐园", completed: false, category: "旅行" },
        { id: 6, text: "学会弹吉他给对方听", completed: false, category: "技能" },
      ]
      setBucketItems(defaultItems)
      StorageService.saveBucketList(defaultItems)
    }
  }, [])

  // 保存数据
  const saveItems = (items: BucketItem[]) => {
    setBucketItems(items)
    StorageService.saveBucketList(items)
  }

  // 添加新项目
  const handleAddItem = (itemData: Omit<BucketItem, 'id'>) => {
    const newItem: BucketItem = {
      ...itemData,
      id: parseInt(generateId()),
      completed: false,
      completedDate: undefined,
      completedNote: undefined
    }
    const updatedItems = [newItem, ...bucketItems]
    setBucketItems(updatedItems)
    StorageService.saveBucketList(updatedItems)
    setShowAddForm(false)
  }

  // 编辑项目
  const handleUpdateItem = (updatedItem: BucketItem) => {
    const updatedItems = bucketItems.map(item => 
      item.id === updatedItem.id ? updatedItem : item
    )
    setBucketItems(updatedItems)
    StorageService.saveBucketList(updatedItems)
    setEditingItem(null)
    setShowAddForm(false)
  }

  // 删除项目
  const deleteItem = (id: number) => {
    if (confirm('确定要删除这个约定吗？')) {
      const updatedItems = bucketItems.filter(item => item.id !== id)
      saveItems(updatedItems)
    }
  }

  // 切换完成状态
  const toggleCompleted = (item: BucketItem) => {
    if (!item.completed) {
      setShowCompletionModal(item)
    } else {
      const updatedItems = bucketItems.map(i => 
        i.id === item.id ? { ...i, completed: false, completedDate: undefined, completedNote: undefined } : i
      )
      saveItems(updatedItems)
    }
  }

  // 完成项目
  const completeItem = (completedNote: string) => {
    if (showCompletionModal) {
      const updatedItems = bucketItems.map(item => 
        item.id === showCompletionModal.id 
          ? { ...item, completed: true, completedDate: new Date().toISOString().split('T')[0], completedNote }
          : item
      )
      saveItems(updatedItems)
      setShowCompletionModal(null)
    }
  }

  const categories = ["全部", "旅行", "技能", "生活", "浪漫"]
  const [selectedCategory, setSelectedCategory] = useState("全部")

  const filteredItems = selectedCategory === "全部" 
    ? bucketItems 
    : bucketItems.filter(item => item.category === selectedCategory)

  const completedCount = bucketItems.filter(item => item.completed).length
  const totalCount = bucketItems.length

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-50 to-blue-50">
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold text-center text-gray-800 mb-8 font-serif">
          未来的约定清单 ✨
        </h1>
        
        <div className="max-w-4xl mx-auto">
          {/* 进度统计 */}
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg mb-8">
            <div className="text-center">
              <h2 className="text-2xl font-semibold text-purple-600 mb-4">我们的进度</h2>
              <div className="flex items-center justify-center space-x-4">
                <div className="text-3xl font-bold text-purple-600">{completedCount}</div>
                <div className="text-gray-500">/</div>
                <div className="text-3xl font-bold text-gray-600">{totalCount}</div>
              </div>
              <p className="text-gray-600 mt-2">已完成的美好约定</p>
              <div className="w-full bg-gray-200 rounded-full h-3 mt-4">
                <div 
                  className="bg-gradient-to-r from-purple-400 to-pink-400 h-3 rounded-full transition-all duration-500"
                  style={{ width: `${(completedCount / totalCount) * 100}%` }}
                ></div>
              </div>
            </div>
          </div>

          {/* 分类筛选 */}
          <div className="flex flex-wrap justify-center gap-3 mb-8">
            {categories.map(category => (
              <button
                key={category}
                onClick={() => setSelectedCategory(category)}
                className={`px-6 py-2 rounded-full transition-all duration-300 ${
                  selectedCategory === category
                    ? 'bg-purple-500 text-white shadow-lg'
                    : 'bg-white/80 text-gray-600 hover:bg-purple-100'
                }`}
              >
                {category}
              </button>
            ))}
          </div>

          {/* 愿望清单 */}
          <div className="grid gap-4">
            <AnimatePresence>
              {filteredItems.map(item => (
                <motion.div
                  key={item.id}
                  layout
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className={`bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-lg transition-all duration-300 hover:shadow-xl ${
                    item.completed ? 'border-l-4 border-green-400' : 'border-l-4 border-purple-400'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-4">
                      <button
                        onClick={() => toggleCompleted(item)}
                        className={`w-6 h-6 rounded-full flex items-center justify-center transition-colors ${
                          item.completed 
                            ? 'bg-green-400 text-white hover:bg-green-500' 
                            : 'bg-gray-200 text-gray-400 hover:bg-purple-200'
                        }`}
                      >
                        {item.completed && '✓'}
                      </button>
                      <div>
                        <h3 className={`text-lg font-medium ${
                          item.completed ? 'text-gray-500 line-through' : 'text-gray-700'
                        }`}>
                          {item.text}
                        </h3>
                        <div className="flex items-center space-x-2 mt-2">
                          <span className="inline-block bg-purple-100 text-purple-600 text-sm px-3 py-1 rounded-full">
                            {item.category}
                          </span>
                          {item.completedDate && (
                            <span className="text-xs text-gray-500">
                              完成于 {item.completedDate}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      {item.completed && (
                        <div className="text-2xl">🎉</div>
                      )}
                      <button
                        onClick={() => setEditingItem(item)}
                        className="text-blue-500 hover:text-blue-700 text-sm"
                      >
                        ✏️
                      </button>
                      <button
                        onClick={() => deleteItem(item.id)}
                        className="text-red-500 hover:text-red-700 text-sm"
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                  {item.completed && item.completedNote && (
                    <div className="mt-4 p-4 bg-green-50 rounded-lg">
                      <p className="text-green-700 text-sm">
                        ✨ {item.completedNote}
                      </p>
                    </div>
                  )}
                </motion.div>
              ))}
            </AnimatePresence>
          </div>

          {/* 添加新愿望按钮 */}
          <motion.button
            onClick={() => setShowAddForm(true)}
            className="mt-8 w-full bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-2xl p-6 shadow-lg hover:from-purple-600 hover:to-pink-600 transition-all"
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
          >
            <div className="text-2xl mb-2">💫</div>
            <h3 className="text-xl font-semibold">添加新的约定</h3>
          </motion.button>

          {/* 表单和模态框 */}
          <BucketItemForm 
            isOpen={showAddForm || editingItem !== null}
            onClose={() => {
              setShowAddForm(false)
              setEditingItem(null)
            }}
            onSubmit={(itemData) => {
              if (editingItem) {
                handleUpdateItem({ ...itemData, id: editingItem.id })
              } else {
                handleAddItem(itemData)
              }
            }}
            initialData={editingItem}
            categories={categories.slice(1)} // 去掉“全部”选项
          />

          <CompletionModal 
            isOpen={showCompletionModal !== null}
            item={showCompletionModal}
            onClose={() => setShowCompletionModal(null)}
            onComplete={completeItem}
          />
        </div>
      </div>
    </div>
  )
}

export const Route = createFileRoute('/bucket-list')({
  component: BucketList,
})
